package com.chinda.modules.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.chinda.common.page.RPage;
import com.chinda.modules.sys.qo.SysUserRoleQO;
import com.chinda.modules.sys.dao.SysUserRoleDao;
import com.chinda.modules.sys.entity.SysUserRoleEntity;
import com.chinda.modules.sys.service.SysUserRoleService;

import java.util.List;
import java.util.stream.Collectors;


/**
 * 用户与角色对应关系
 *
 * @author chinda
 * @date 2021-06-16 05:52:51
 */
@Service("sysUserRoleService")
@Transactional(readOnly = true, rollbackFor = Exception.class)
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleDao, SysUserRoleEntity> implements SysUserRoleService {

    /**
     * 获取分页信息
     *
     * @param qo
     * @return
     */
    @Override
    public RPage page(SysUserRoleQO qo) {
        return new RPage(page(qo.getPage(), qo.getQueryWrapper()));
    }

    /**
     * 保存用户与角色关系
     *
     * @param userId
     * @param roleIdList
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserRole(Long userId, List<Long> roleIdList) {

        // 先根据用户id删除角色关系
        this.remove(new QueryWrapper<SysUserRoleEntity>().eq("user_id", userId));

        // 保存用户与角色关系
        if (CollUtil.isNotEmpty(roleIdList)) {
            List<SysUserRoleEntity> sysUserRoleList = roleIdList
                    .stream()
                    .map(roleId -> {
                        SysUserRoleEntity sysUserRoleEntity = new SysUserRoleEntity();
                        sysUserRoleEntity.setUserId(userId);
                        sysUserRoleEntity.setRoleId(roleId);
                        return sysUserRoleEntity;
                    })
                    .collect(Collectors.toList());
            this.saveBatch(sysUserRoleList);
        }
    }
}